package com.ziyun.erp.common.utils;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.ConvolveOp;
import java.awt.image.Kernel;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;


/**
 * 图片工具类
 *
 * @author gaosheng
 * @date 2018-09-27 10:49
 */
public class ImageUtils {

    /**
     * @param originalFile 原文件
     * @param resizedFile  压缩目标文件
     * @param newWidth     压缩后的图片宽度
     * @param quality      压缩质量（0到1之间，越高质量越好）
     * @throws IOException
     */
    public static void resize(File originalFile, File resizedFile,
                              int newWidth, float quality) throws IOException {

        if (quality > 1) {
            throw new IllegalArgumentException(
                    "Quality has to be between 0 and 1");
        }

        ImageIcon ii = new ImageIcon(originalFile.getCanonicalPath());
        Image i = ii.getImage();
        Image resizedImage = null;

        int iWidth = i.getWidth(null);
        System.out.println("iWidth:" + iWidth);
        int iHeight = i.getHeight(null);
        System.out.println("iHeight:" + iHeight);
        if (iWidth > iHeight) {
            resizedImage = i.getScaledInstance(newWidth, (newWidth * iHeight)
                    / iWidth, Image.SCALE_SMOOTH);
        } else {
            resizedImage = i.getScaledInstance((newWidth * iWidth) / iHeight,
                    newWidth, Image.SCALE_SMOOTH);
        }

        // 获取图片中的所有像素
        Image temp = new ImageIcon(resizedImage).getImage();

        // 创建缓冲
        BufferedImage bufferedImage = new BufferedImage(temp.getWidth(null),
                temp.getHeight(null), BufferedImage.TYPE_INT_RGB);

        // 复制图片到缓冲流中
        Graphics g = bufferedImage.createGraphics();

        // 清除背景并开始画图
        g.setColor(Color.white);
        g.fillRect(0, 0, temp.getWidth(null), temp.getHeight(null));
        g.drawImage(temp, 0, 0, null);
        g.dispose();

        // 柔和图片.
        float softenFactor = 0.05f;
        float[] softenArray = {0, softenFactor, 0, softenFactor,
                1 - (softenFactor * 4), softenFactor, 0, softenFactor, 0};
        Kernel kernel = new Kernel(3, 3, softenArray);
        ConvolveOp cOp = new ConvolveOp(kernel, ConvolveOp.EDGE_NO_OP, null);
        bufferedImage = cOp.filter(bufferedImage, null);

        /*FileOutputStream out = new FileOutputStream(resizedFile);
        JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
        JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(bufferedImage);
        param.setQuality(quality, true);
        encoder.setJPEGEncodeParam(param);
        encoder.encode(bufferedImage);
        bufferedImage.flush();
        out.close();*/

        // JPEGImageEncoder jar 包问题，使用 ImageIO
        ImageIO.write(bufferedImage, "jpeg", resizedFile);
        bufferedImage.flush();
    }

    public static void download(String url, String fileName, String filePath) {
        File file = new File(filePath);
        if (!file.exists()) {
            file.mkdirs();
        }
        FileOutputStream fileOut = null;
        HttpURLConnection conn = null;
        InputStream inputStream = null;
        try {
            URL httpUrl = new URL(url);
            conn = (HttpURLConnection) httpUrl.openConnection();
            conn.connect();
            inputStream = conn.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(inputStream);
            fileOut = new FileOutputStream(file.getPath() + File.separator + fileName);
            BufferedOutputStream bos = new BufferedOutputStream(fileOut);
            byte[] buf = new byte[1024];
            int length = bis.read(buf);
            while (length != -1) {
                bos.write(buf, 0, length);
                length = bis.read(buf);
            }
            bos.close();
            bis.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (conn != null) {
                conn.disconnect();
            }
        }
    }

    /**
     * 网络图片base64编码
     *
     * @param strUrl
     * @return
     * @throws Exception
     */
    public static byte[] getImageFromNetByUrl(String strUrl) throws Exception {
        try {
            if (null == strUrl) {
                return null;
            }
            URL url = new URL(strUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5 * 1000);
            InputStream inStream = conn.getInputStream();// 通过输入流获取图片数据
            byte[] btImg = readInputStream(inStream);// 得到图片的二进制数据
            return btImg;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static byte[] readInputStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        inStream.close();
        return outStream.toByteArray();
    }

    public static void main(String[] args) throws IOException {
//        File originalImage = new File("C:\\Users\\ZiYun1127\\Desktop\\11.jpg");
//        BufferedImage sourceImg = ImageIO.read(new FileInputStream(originalImage));
//        int width = sourceImg.getWidth();
//        int height = sourceImg.getHeight();
//        ImageUtils.resize(originalImage, new File("C:\\Users\\ZiYun1127\\Desktop\\11_copy.jpg"), (int) (width * 0.7), 0.7f);

        long timeMillis = System.currentTimeMillis();
        download("http://images.11ziyun.com/upload/201809/11/78/40dbcce4178620feaab83663316c513f.jpeg"
                , "40dbcce4178620feaab83663316c513f.jpeg"
                , "C:\\Users\\ZiYun1127\\Desktop\\");
        System.out.println((System.currentTimeMillis() - timeMillis));
    }
}
